package com.longnuoqi.mydoctor.activity;


import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;

import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.longnuoqi.mydoctor.entity.Disease;
import com.longnuoqi.mydoctor.fragment.ZizhenListFragment;
import com.longnuoqi.mydoctor.utils.ActivityCollection;
import com.longnuoqi.mydoctor.utils.FileUtil;
import com.yunhe.mydoctor.R;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Lenovo on 2015/12/27.
 */
public class ZizhenClassifyActivity extends AppCompatActivity {
    private ImageView back;
    private ListView listView;
    private static final String url = "http://www.tngou.net/api/department/all";
    private static final String name = "disease_department_list.txt";
    private List<Disease> list;
    private SimpleAdapter adapter;

    private static boolean isExit = false;//判断是否退出
    private static boolean hasTask = false;//判断是否是任务
    private Timer timer = new Timer();//声明timer对象，计时器
    private TimerTask timerTask = new TimerTask() {//为timer安排一次执行或重复执行的任务
        @Override
        public void run() {
            isExit = false;
        }
    };

    /*双击退出程序*/
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (!isExit) {
                isExit = true;
                Toast.makeText(ZizhenClassifyActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                if (!hasTask) {
                    timer.schedule(timerTask, 2000);//安排在指定延迟后执行指定的任务
                }
            } else {
                ActivityCollection.finishAll();
                //回收资源
                System.exit(0);
            }
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.zizhen_classify_layout);
        ActivityCollection.addActivity(this);
        init();
        getData();
    }

    private void init() {
        back = (ImageView) findViewById(R.id.zizhen_back_btn);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = getIntent();
                setResult(RESULT_OK, intent);
                finish();
            }
        });

        listView = (ListView) findViewById(R.id.zizhen_listview);
    }

    private void getData() {
        if (!FileUtil.fileIsExist(name)) {
            Log.e("==============", "file:" + name + ":is not exist");
            RequestQueue queue = Volley.newRequestQueue(ZizhenClassifyActivity.this);
            StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
                @Override
                public void onResponse(String s) {
                    FileUtil.saveFile(s, name);
                    list = FileUtil.jsonDepartment(s);
                    initListView();
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                }
            });
            queue.add(request);
        } else {
            Log.e("==============", "file:" + name + ":exist");
            String s = FileUtil.readFile(name);
            list = FileUtil.jsonDepartment(s);
            initListView();
        }
    }

    private void initListView() {
        List<Map<String, String>> mapList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            Map<String, String> map = new HashMap<>();
            map.put("name", list.get(i).getName());
            mapList.add(map);
        }

        adapter = new SimpleAdapter(this, mapList, R.layout.zizhen_classify_listview_item, new String[]{"name"}, new int[]{R.id.zizhen_listview_text});
        listView.setAdapter(adapter);

        Bundle bundle = new Bundle();
        bundle.putInt("id", 1);
        bundle.putInt("position", 0);
        showFragment(bundle);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Bundle bundle = new Bundle();
                bundle.putInt("id", list.get(position).getId());
                bundle.putInt("position", position);
                showFragment(bundle);
            }
        });
    }


    private void showFragment(Bundle bundle) {
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        Fragment fragment = new ZizhenListFragment();
        fragment.setArguments(bundle);
        transaction.replace(R.id.zizhen_framelayout, fragment);
        transaction.commit();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityCollection.removeActivity(this);
    }


}
